<?php

namespace App\Http\Controllers\manage;

use App\groupModel;
use App\Http\Controllers\Controller;
use App\userInfosModel;
use App\userModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Validator;

class userController extends Controller
{
    public function index(Request $request)
    {
        //当前页面标题
        $title = '账户管理';
        $userModel = new userModel();

        //接收参数
        $page['currentPage'] = $request->get('page');
        $groupBy = $request->input('group');
        $searchBy = $request->input('search');

        if (empty($searchBy) && empty($groupBy)) {
            //显示所有用户
            $users = $userModel->leftJoin('groups', 'users.GID', '=', 'groups.GID')
                ->leftJoin('user_infos', 'users.IID', '=', 'user_infos.IID')
                ->select('UID', 'user_infos.IID', 'groups.GID', 'user', 'user_infos.name as Uname', 'groups.name as Gname', 'head')
                ->Paginate(PAGE_SIZE);
        } elseif (!empty($searchBy) && empty($groupBy)) {
            //显示搜索结果
            $users = $userModel->leftJoin('groups', 'users.GID', '=', 'groups.GID')
                ->leftJoin('user_infos', 'users.IID', '=', 'user_infos.IID')
                ->select('UID', 'user_infos.IID', 'groups.GID', 'user', 'user_infos.name as Uname', 'groups.name as Gname', 'head')
                ->where('user', 'like', '%' . $searchBy . '%')
                ->orWhere('user_infos.name', 'like', '%' . $searchBy . '%')
                ->orWhere('groups.name', 'like', '%' . $searchBy . '%')
                ->Paginate(PAGE_SIZE);
        } elseif (empty($searchBy) && !empty($groupBy)) {
            //显示分组筛选结果
            $users = $userModel->leftJoin('groups', 'users.GID', '=', 'groups.GID')
                ->leftJoin('user_infos', 'users.IID', '=', 'user_infos.IID')
                ->select('UID', 'user_infos.IID', 'groups.GID', 'user', 'user_infos.name as Uname', 'groups.name as Gname', 'head')
                ->where('groups.GID', '=', $groupBy == 'null' ? null : $groupBy)
                ->Paginate(PAGE_SIZE);
        } elseif (!empty($searchBy) && !empty($groupBy)) {
            //显示分组的搜索结果
            $users = $userModel->leftJoin('groups', 'users.GID', '=', 'groups.GID')
                ->leftJoin('user_infos', 'users.IID', '=', 'user_infos.IID')
                ->select('UID', 'user_infos.IID', 'groups.GID', 'user', 'user_infos.name as Uname', 'groups.name as Gname', 'head')
                ->where('groups.GID', '=', $groupBy == 'null' ? null : $groupBy)
                ->where(function ($query) use ($searchBy) {
                    $query->where('user', 'like', '%' . $searchBy . '%')
                        ->orWhere('user_infos.name', 'like', '%' . $searchBy . '%')
                        ->orWhere('groups.name', 'like', '%' . $searchBy . '%');
                })->Paginate(PAGE_SIZE);
        }

        //当前结果总数
        $currentTotal = $users->total();
        //准备页码
        $totalPage = ceil($currentTotal / PAGE_SIZE);
        if ($page['currentPage'] > $totalPage || $page['currentPage'] < 1) $page['currentPage'] = 1;
        $prePage = $page['currentPage'] > 1 ? $page['currentPage'] - 1 : 1;
        $nextPage = $page['currentPage'] < $totalPage ? $page['currentPage'] + 1 : $totalPage;
        $page['head'] = '?page=1&search=' . $searchBy . '&group=' . $groupBy;
        $page['pre'] = '?page=' . $prePage . '&search=' . $searchBy . '&group=' . $groupBy;
        $page['next'] = '?page=' . $nextPage . '&search=' . $searchBy . '&group=' . $groupBy;
        $page['tail'] = '?page=' . $totalPage . '&search=' . $searchBy . '&group=' . $groupBy;

        foreach ($users as $user) {
            if ($user->GID == null)
                $user->Gname = '未分组';
            if ($user->IID == null) {
                $user->Uname = '未设置';
                $user->head = 'default';
            }
        }
        //分组信息
        $groups = groupModel::get();
        return view("manage/user", compact('title', 'users', 'page', 'currentTotal', 'searchBy', 'groupBy', 'groups'));
    }

    //返回请求的头像
    public function head(Request $request)
    {
        $headCode = $request->input('file');
        if (!Storage::exists("head/$headCode")) {
            $headCode = 'default';
        }
        return Storage::get("head/$headCode");
    }

    //删除用户
    public function userDel()
    {
        $urlStr = $_SERVER['QUERY_STRING'];
        $data = str_replace(array('-', '_'), array('+', '/'), $urlStr);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        $UID = explode('=', base64_decode($data))[1];
        userModel::where('UID', $UID)->delete();
        return back();
    }

    //添加/编辑用户
    public function userEdit(Request $request)
    {
        if ($request->isMethod('post')) {
            $userModel = new userModel();
            $userInfoModel = new userInfosModel();
            $UID = $request->get('UID');

            if ($UID == null) {
                //新建用户
                $messages = [
                    'username.required' => '您没有填写 用户名',
                    'pwd.required' => '您没有填写 密码',
                    'name.required' => '您没有填写 昵称'
                ];

                $rules = [
                    'username' => 'required',
                    'pwd' => 'required',
                    'name' => 'required'
                ];

                $validator = Validator::make($request->input(), $rules, $messages);
                $validator->validate();

                $userInfoModel->contact = $request->input('contact');
                $userInfoModel->name = $request->input('name');
                $userInfoModel->head = 'default';
                $userInfoModel->save();
                $userModel->IID = $userInfoModel->IID;
                $userModel->pwd = $request->input('pwd');
                $userModel->user = $request->input('username');

                if ($request->input('GID') == 'null')
                    $userModel->GID = null;
                else
                    $userModel->GID = $request->input('GID');
                $userModel->save();

                $validator->errors()->add('user', '用户添加成功！');
                return back()->withErrors($validator);
            } else {
                //编辑用户
                $messages = [
                    'name.required' => '您没有填写 昵称'
                ];

                $rules = [
                    'name' => 'required'
                ];

                $validator = Validator::make($request->input(), $rules, $messages);
                $validator->validate();

                $IID = $request->input('IID');
                $newUserInfo = $userInfoModel->where('IID', $IID)->first();
                $newUserInfo->contact = $request->input('contact');
                $newUserInfo->name = $request->input('name');
                $newUserInfo->save();

                $newUser = $userModel->where('UID', $UID)->first();
                if ($request->input('GID') == 'null')
                    $newUser->GID = null;
                else
                    $newUser->GID = $request->input('GID');
                $newUser->save();
                $validator->errors()->add('user', '修改已保存');
                return back()->withErrors($validator);
            }
        } else {
            if (empty($UID = $request->input('UID'))) {
                //当前页面标题
                $title = '添加用户';
            } else {
                //当前页面标题
                $title = '编辑用户';
                $user = userModel::leftJoin('groups', 'users.GID', '=', 'groups.GID')
                    ->leftJoin('user_infos', 'users.IID', '=', 'user_infos.IID')
                    ->where('UID', $UID)->first();
            }
            $groups = groupModel::get();
            return view("manage/user_edit", compact('title', 'groups', 'user'));
        }
    }

    /*//处理头像上传
    public function headUpload()
    {

    }*/
}
